import time

from django.shortcuts import render, HttpResponse, redirect
from web.forms.account import RegisterModelForm, SendSmsForm, LoginForm
from web.forms.data import DevinfoModelForm, DevinfodetailModelForm, ModelInfoModelForm

from django.http import JsonResponse
from utils.imagecode import check_code
from io import BytesIO
from django.views.decorators.csrf import csrf_exempt
from web import models
from django.db.models import Q
import cv2
import json
import paho.mqtt.client as mqtt
import datetime
import os
from django.forms.models import model_to_dict
from django.utils.safestring import mark_safe
import random
import threading
import schedule

port = 1883
host = '47.100.182.245'

global phone


def on_connect(client, userdata, flags_dict, rc):
    print("Connected with result code " + str(rc))


def on_disconnect(client, userdata, flags_dict, rc):
    print("Disconnected.")


def on_message(client, userdata, msg):
    try:
        # phone_field = models.UserInfo.objects.get(mobile_phone=phone);
        print(msg.payload.decode())
        if msg.payload.decode() == 'I am Alive':
            print('ok')
            return
        message = json.loads(msg.payload.decode())
        type = message["type"]
        data = message["data"]
        topic = msg.topic
        # print(type, data, str(topic))
        obj = models.DevInfo.objects.filter(devtopic=topic).first()
        devtopic = obj.id
        phonecheck = obj.mobile_phone
        mes = ''
        i = 0
        if type == "sensor":
            findobjs = models.Trigger.objects.filter(mobile_phone=phonecheck).filter(triggercalling=topic)
            if findobjs.exists():
                for obj in findobjs:
                    print(obj.triggerdata, data)
                    if obj.triggerdata == data:
                        buf = "{'data':'" + obj.pubdata + "' ,'type':'sensor'}"
                        buffer = json.dumps(eval(buf))
                        client.publish(obj.triggercalled, buffer, qos=0)

                        mes = '触发事件' + obj.triggername
                        id = models.DevInfo.objects.filter(devtopic=topic).first().id
                        triggerevent = models.DeviceData(mobile_phone=phonecheck, devdata=str(data), datadetail=mes,
                                                         send_flag='发布',
                                                         devtopic_id=id, triggerset=mes, characteristic='sensor')
                        savetime = time.strftime('%Y-%m-%d %H:%M:%S ', time.localtime(time.time()))
                        triggerevent.save()
                        updatetime = models.Trigger.objects.filter(id=obj.id).update(triggersavetime=savetime)
                        i += 1
            if i == 0:
                sensor = models.DeviceData(mobile_phone=phonecheck, devdata=str(data), datadetail=str(data),
                                           send_flag='订阅', devtopic_id=devtopic, characteristic='sensor')
                sensor.save()
            print("save", str(data), mes)
        elif type == "video":
            videoname = message["videoname"]
            byteArr = bytes(eval(data))
            open_str = "./web/static/img/video/"
            open_path = open_str + videoname + ".jpg"
            obj = models.DevInfo.objects.filter(mobile_phone=phonecheck).filter(devtopic=topic).first()
            if obj.srcpath == None:
                f = open(open_path, "wb+")
                f.write(byteArr)
                f.close()
                video = models.DeviceData(mobile_phone=phonecheck, devdata=' ', send_flag='订阅',
                                          devtopic_id=obj.id, characteristic='video')
                video.save()
                models.DevInfo.objects.filter(mobile_phone=phonecheck).filter(devtopic=topic).update(
                    srcpath=open_path)
                print("save type1")
                pass
            else:
                if obj.srcpath != open_path:
                    os.remove(obj.srcpath)
                    f = open(open_path, "wb+")
                    f.write(byteArr)
                    f.close()
                    video = models.DeviceData(mobile_phone=phonecheck, devdata=' ', send_flag='订阅',
                                              devtopic_id=obj.id, characteristic='video')
                    video.save()
                    models.DevInfo.objects.filter(mobile_phone=phonecheck).filter(devtopic=topic).update(
                        srcpath=open_path)
                    print("save type2")
                else:
                    f = open(open_path, "wb+")
                    f.write(byteArr)
                    f.close()
                    video = models.DeviceData(mobile_phone=phonecheck, devdata=' ', send_flag='订阅',
                                              devtopic_id=obj.id, characteristic='video')
                    video.save()
                    models.DevInfo.objects.filter(mobile_phone=phonecheck).filter(devtopic=topic).update(
                        srcpath=open_path)
                    print("save type3")
        elif type == "web":
            websend = models.DeviceData(mobile_phone=phonecheck, devdata=str(data), datadetail=str(data),
                                        send_flag='订阅', devtopic_id=devtopic, characteristic='web')
            websend.save()
            print("save", str(data), mes)

    except:
        print('recv error!')
        return


# client.loop_forever()


def runforever():
    while True:
        schedule.run_pending()
        time.sleep(1)

# def checkplanforever():
#     while True:
#         schedule.run_pending()
#         all_jobs = schedule.get_jobs()
#         print(all_jobs)
#         time.sleep(20)

def checkthreadforever():
    flag1 = 0
    flag2 = 0
    while True:
        flag1 = 0
        flag2 = 0
        all_threads = threading.enumerate()
        for thread in all_threads:
            if thread.getName() == 'schedule':
                flag1 = 1
        if flag1 == 0:
            print('schedule_thread died')
            schedule_thread = threading.Thread(target=runforever, name='schedule')
            schedule_thread.start()
        time.sleep(60)


client = mqtt.Client('w11eb')
client.username_pw_set("admin", "pu12ic")  # 输入账户密码 没有的话可以省略
client.on_connect = on_connect
client.on_message = on_message
client.connect(host=host, port=port, keepalive=3600)
client.subscribe('keepalive')
client.loop_start()
print("connect ok")

def checkflag(name):
    global phone
    objs = models.Scheduletask.objects.filter(mobile_phone=phone)
    if objs.exists():
        for obj in objs:
            if not schedule.get_jobs(obj.taskname):
                models.Scheduletask.objects.filter(mobile_phone=phone).filter(taskname=obj.taskname).update(
                    flag="过期失效")

def keepali(name):  # 心跳保活
    client.publish('keepalive', 'I am Alive', qos=0)

schedule_thread = threading.Thread(target=runforever, name='schedule')
schedule_thread.start()
# checkplan_thread = threading.Thread(target=checkplanforever, name='checkplan')
# checkplan_thread.start()

schedule.every(30).minutes.do(keepali, 'admin').tag('abcdefghijklmn')

checkthreadplan_thread = threading.Thread(target=checkthreadforever, name='checkthread')
checkthreadplan_thread.start()

# 个人主页
def index(request):
    global phone
    phone = request.tracer.mobile_phone
    objstarts = models.DevInfo.objects.filter(flag='订阅中')
    for objstart in objstarts:
        client.subscribe(objstart.devtopic)
        client.loop_start()
        print("sub topic:" + objstart.devtopic)

    if not schedule.get_jobs('abcdefghijk'):
        schedule.every(1).minutes.do(checkflag, 'admin').tag('abcdefghijk')

    devall = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).count()
    devsub = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(flag='订阅中').count()
    devpub = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(send_flag='2').count()

    datatrigger = models.DeviceData.objects.filter(mobile_phone=request.tracer.mobile_phone)
    count = 0
    for i in datatrigger:
        if i.triggerset != None:
            count = count + 1

    return render(request, 'index.html', {'devall': devall, 'devsub': devsub, 'devpub': devpub, 'triggercount': count})


# 展示头像
def showimg(request):
    phone = request.GET.get("phone")
    src = models.UserInfo.objects.filter(mobile_phone=phone).first().imgsrc
    if src != None:
        return JsonResponse({"status": True, "scrpath": src})
    return JsonResponse({"status": False})

def video(request):
    return render(request, 'video.html')

# 按帧数播放录像
def sendvideo(request):
    if (request.GET["check_video"] == "点击打开"):
        client.subscribe('aaa', 1)  # 订阅主题test

        client.loop_start()
        return JsonResponse({'status': "1"})
    elif (request.GET["check_video"] == "点击关闭"):
        client.unsubscribe('aaa', 1)
        return JsonResponse({'status': "2"})
    else:
        return JsonResponse({'status': "Unknown", 'error': "打开失败请检查设置"})


# 模板详情
def devicetemp(request):
    global phone
    phone = request.tracer.mobile_phone
    info = models.UserInfo.objects.filter(username=request.tracer.username).first()
    objstarts = models.DevInfo.objects.filter(flag='订阅中')
    for objstart in objstarts:
        client.subscribe(objstart.devtopic)
        client.loop_start()
    form = ModelInfoModelForm()
    temp_str = models.ModelInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).order_by("-devrecord")

    return render(request, "devicetemp.html", {"form": form, "temp": temp_str})


# 模板删除
def tempdel(request):
    nid = request.GET.get("nid")
    models.ModelInfo.objects.filter(id=nid).delete()
    return redirect("/web/device/temp")


# 模板内容加载
def temload(request):
    temload_list = []
    dict_list = {}
    temps = models.ModelInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).order_by("-devrecord")
    i = 0
    if temps.exists():
        for temp in temps:
            temload_list = []
            topics = models.ModelPart.objects.filter(ModelID_id=temp.id)
            if topics.exists():
                i = 0
                for topic in topics:
                    i = i + 1
                    if i > 4:
                        ele = "<div>...</div>"
                        temload_list.append(ele)
                        break
                    else:
                        ele = "<div>{}</div>".format(topic.reltopic_id)
                        temload_list.append(ele)
                temload_str = mark_safe("".join(temload_list))
                dict_list[str(temp.id)] = temload_str
            else:
                ele = "<div>Null</div>"
                temload_list.append(ele)
                temload_str = mark_safe("".join(temload_list))
                dict_list[str(temp.id)] = temload_str

        return JsonResponse({"status": True, "dict_list": dict_list})
    else:
        return JsonResponse({"status": False})


# 关联模板详情关联设备展示
def relshow(request):
    mid = request.GET.get("mid")
    print(mid)
    findshows = models.ModelPart.objects.filter(ModelID_id=mid)
    find_list = []
    unfind_list = []
    findact_list = []
    unfindact_list = []
    modelname = models.ModelInfo.objects.filter(id=mid).first().modelname
    tables = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone)
    sel_list = []
    if findshows.exists():
        for findshow in findshows:
            sel_list.append(findshow.reltopic_id)

        find_tables = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
            devtopic__in=sel_list)
        unfind_tables = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).exclude(
            devtopic__in=sel_list)

        for find_table in find_tables:
            str = find_table.devtopic
            ele = "<div style='height: 40px'>{}</div>".format(str)
            find_list.append(ele)
            ele = "<div style='height: 40px'><a topic='{}' class='btn btn-primary btndell'>删除</a></div>".format(str)
            findact_list.append(ele)
        for unfind_table in unfind_tables:
            str = unfind_table.devtopic
            ele = "<div style='height: 40px'>{}</div>".format(str)
            unfind_list.append(ele)
            ele = "<div style='height: 40px'><a topic='{}' class='btn btn-primary btnaddd'>关联 </a></div>".format(str)
            unfindact_list.append(ele)
        find_str = mark_safe("".join(find_list))
        unfind_str = mark_safe("".join(unfind_list))
        findact_str = mark_safe("".join(findact_list))
        unfindact_str = mark_safe("".join(unfindact_list))
        return JsonResponse(
            {"status": True, "find": find_str, "unfind": unfind_str, "findact": findact_str,
             "unfindact": unfindact_str, "modelname": modelname, "mid": mid})
    else:
        for table in tables:
            str = table.devtopic
            ele = "<div>{}</div>".format(str)
            unfind_list.append(ele)
            ele = "<div><a topic='{}' class='btn btn-primary btnaddd'>关联 </a></div>".format(str)
            unfindact_list.append(ele)

        find_str = mark_safe("".join(find_list))
        unfind_str = mark_safe("".join(unfind_list))
        findact_str = mark_safe("".join(findact_list))
        unfindact_str = mark_safe("".join(unfindact_list))
        return JsonResponse(
            {"status": True, "find": find_str, "unfind": unfind_str, "findact": findact_str,
             "unfindact": unfindact_str, "modelname": modelname, "mid": mid})


# 模板关联设备添加ajax
def reladd(request):
    topic = request.GET.get("topic")
    modelname = request.GET.get("modelname")
    print(topic, modelname)
    mid = models.ModelInfo.objects.filter(modelname=modelname).first().id
    sav = models.ModelPart(ModelID_id=mid, reltopic_id=topic)
    sav.save()

    return JsonResponse({"status": True})


# 模板关联设备删除ajax
def reldel(request):
    topic = request.GET.get("topic")
    modelname = request.GET.get("modelname")
    mid = models.ModelInfo.objects.filter(modelname=modelname).first().id
    print(topic, modelname, mid)
    models.ModelPart.objects.filter(ModelID_id=mid).filter(reltopic_id=topic).delete()

    return JsonResponse({"status": True})


# 添加模板页面ajax
@csrf_exempt
def tempadd(request):
    form = ModelInfoModelForm(data=request.POST)
    # models.DeviceData(mobile_phone=phone, devdata=str(data), send_flag='订阅',
    #                   devtopic_id=devtopicpk.devtopic)
    if form.is_valid():
        form.save()
        return JsonResponse({"status": True})
    return JsonResponse({"status": False, "error": form.errors})


# 编辑模板
@csrf_exempt
def tempedit(request):
    editid = request.GET.get("editid")
    row_proj = models.ModelInfo.objects.filter(id=editid).first()
    if not row_proj:
        return JsonResponse({"status": False, "error": "编辑失败"})

    form = ModelInfoModelForm(data=request.POST, instance=row_proj)
    if form.is_valid():
        modelname = form.cleaned_data["modelname"]
        detail = form.cleaned_data["detail"]
        models.ModelInfo.objects.filter(id=editid).update(modelname=modelname)
        models.ModelInfo.objects.filter(id=editid).update(detail=detail)
    return JsonResponse({"status": True, "success": "修改成功"})


# 编辑模板
def editsearch(request):
    editid = request.GET.get("editid")
    row_proj = models.ModelInfo.objects.filter(id=editid).values("mobile_phone_id", "modelname", "detail").first()
    if not row_proj:
        return JsonResponse({"status": False, "error": "编辑失败"})
    return JsonResponse({"status": True, "data": row_proj})


# 模板对应topic发布ajax
@csrf_exempt
def temppub(request):
    topic = request.POST.get("topic")
    data = request.POST.get("data")
    if models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
            devtopic=topic).exists() or data == None:
        buf = "{'data':'" + data + "' ,'type':'web'}"
        buffer = json.dumps(eval(buf))
        client.publish(topic, buffer, qos=0)

        id = models.DevInfo.objects.filter(devtopic=topic).first().id
        pubsav = models.DeviceData(mobile_phone=request.tracer.mobile_phone, devdata=str(data), datadetail=str(data),
                                   send_flag='发布',
                                   devtopic_id=id, characteristic='web')
        pubsav.save()
        return JsonResponse({"status": True})
    return JsonResponse({"status": False})


# 管理页面也可以发布
@csrf_exempt
def manpub(request):
    mid = request.POST.get("mid")
    data = request.POST.get("data")
    obj = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(id=mid)
    if obj.exists() and data != '':
        topic = obj.first().devtopic
        buf = "{'data':'" + data + "' ,'type':'web'}"
        print(buf)
        buffer = json.dumps(eval(buf))
        client.publish(topic, buffer, qos=0)
        pubsav = models.DeviceData(mobile_phone=request.tracer.mobile_phone, devdata=str(data), datadetail=str(data),
                                   send_flag='发布', devtopic_id=mid, characteristic='web')
        pubsav.save()
        return JsonResponse({"status": True})
    return JsonResponse({"status": False})


# 相应模板内各个模块展示
def devicemodel(request):
    nid = request.GET.get("nid")
    modelsub_list = []
    modelsub_list.append("<div class='row'>")
    model_video = []
    modelparts = models.ModelPart.objects.filter(ModelID_id=nid)
    count = 1
    publist = []
    weidingyue = './web/static/img/video/weidingyue.jpg'
    if modelparts.exists():
        for modelpart in modelparts:
            objects = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
                devtopic=modelpart.reltopic_id)
            if objects.exists():
                object = objects.first()
                if object.devtype == '1' and object.send_flag == "1":
                    datas = models.DeviceData.objects.filter(devtopic_id=object.id)
                    if datas.exists():
                        if object.flag == '未订阅':
                            data = "未订阅"
                        else:
                            data = models.DeviceData.objects.filter(devtopic=object.id).order_by(
                                "-datarecord").first().devdata
                        if count % 3 == 0:
                            ele = '<div class="col-md-4"><div class="widget style1 navy-bg"><div class="row"><div class="col-xs-4"><i class="fa fa-gears fa-5x"></i></div><div class="col-xs-8" style="text-align: center"><strong><h2>{}</h2></strong><h1 class="font-bold">{}　{}</h1></div></div></div></div>' \
                                .format(object.devname, data, object.devsym)
                            modelsub_list.append(ele)
                            modelsub_list.append("</div><div class='row'>")
                        else:
                            ele = '<div class="col-md-4"><div class="widget style1 navy-bg"><div class="row"><div class="col-xs-4"><i class="fa fa-gears fa-5x"></i></div><div class="col-xs-8" style="text-align: center"><strong><h2>{}</h2></strong><h1 class="font-bold">{}　{}</h1></div></div></div></div>' \
                                .format(object.devname, data, object.devsym)
                            modelsub_list.append(ele)
                        count = count + 1
                    else:
                        if count % 3 == 0:
                            data = "Null"
                            ele = '<div class="col-md-4"><div class="widget style1 navy-bg"><div class="row"><div class="col-xs-4"><i class="fa fa-gears fa-5x"></i></div><div class="col-xs-8" style="text-align: center"><strong><h2>{}</h2></strong><h1 class="font-bold">{}　{}</h1></div></div></div></div>' \
                                .format(object.devname, data, object.devsym)
                            modelsub_list.append(ele)
                            modelsub_list.append("</div><div class='row'>")
                        else:
                            data = "Null"
                            ele = '<div class="col-md-4"><div class="widget style1 navy-bg"><div class="row"><div class="col-xs-4"><i class="fa fa-gears fa-5x"></i></div><div class="col-xs-8" style="text-align: center"><strong><h2>{}</h2></strong><h1 class="font-bold">{}　{}</h1></div></div></div></div>' \
                                .format(object.devname, data, object.devsym)
                            modelsub_list.append(ele)
                        count = count + 1
            else:
                ele = '<h1><strong>请检查订阅主题</strong></h1>'
                modelsub_list.append(ele)
                model_str = mark_safe("".join(modelsub_list))
        modelsub_list.append("</div>")
        model_str = mark_safe("".join(modelsub_list))
        for modelpart in modelparts:
            objects = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
                devtopic=modelpart.reltopic_id)
            if objects.exists():
                object = objects.first()
                if object.devtype == '2' and object.send_flag == "1":
                    if object.flag == '订阅中':
                        path = object.srcpath
                        if path == None:
                            ele = '<div class="row" style="text-align:center"><h1>{}</h1></div><div class="divvideo"><img src="/web/static/img/Null.jpg" style="width: 100%;  height: 100%;  object-fit: cover;"></div>'.format(
                                object.devname)
                        else:
                            ele = '<div class="row" style="text-align:center"><h1>{}</h1></div><div class="divvideo"><img id="{}" src="{}" style="width: 100%;  height: 100%;  object-fit: cover;"></div>'.format(
                                object.devname, object.id, path[1:])
                        model_video.append(ele)
                    else:
                        ele = '<div class="row" style="text-align:center"><h1>{}</h1></div><div class="divvideo"><img id="{}" src="{}" style="width: 100%;  height: 100%;  object-fit: cover;"></div>'.format(
                            object.devname, object.id, weidingyue[1:])
                        model_video.append(ele)
        model_video = mark_safe("".join(model_video))
    else:
        ele = '<h1><strong>请检查模板</strong></h1>'
        modelsub_list.append(ele)
        model_str = mark_safe("".join(modelsub_list))
    pubobjs = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(send_flag='2')
    partpubs = models.ModelPart.objects.filter(ModelID_id=nid)
    for pubobj in pubobjs:
        for partpub in partpubs:
            if partpub.reltopic_id == pubobj.devtopic:
                publist.append(partpub.reltopic_id)
    return render(request, 'devicemodel.html',
                  {"modellist": model_str, "modelvideo": model_video, "mid": nid, "pubobj": publist})


# 刷新数据模块展示ajax
def modelshow(request):
    nid = request.GET.get("nid")
    modelsub_list = []
    modelsub_list.append("<div class='row'>")
    count = 1
    modelparts = models.ModelPart.objects.filter(ModelID_id=nid)
    if modelparts.exists():
        for modelpart in modelparts:
            object = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
                devtopic=modelpart.reltopic_id).first()
            if object.devtype == '1' and object.send_flag == "1":
                datas = models.DeviceData.objects.filter(devtopic=object.id)
                if datas.exists():
                    if object.flag == '未订阅':
                        data = "未订阅"
                    else:
                        data = models.DeviceData.objects.filter(devtopic=object.id).order_by(
                            "-datarecord").first().devdata
                    if count % 3 == 0:
                        ele = '<a class="showdata1" href="#" topic="{}" title="点击展示数据"><div class="col-md-4"><div class="widget style1 navy-bg"><div class="row"><div class="col-xs-4"><i class="fa fa-gears fa-5x"></i></div><div class="col-xs-8" style="text-align: center"><strong><h2>{}</h2></strong><h1 class="font-bold">{}　{}</h1></div></div></div></div></a>' \
                            .format(object.id, object.devname, data, object.devsym)
                        modelsub_list.append(ele)
                        modelsub_list.append("</div><div class='row'>")
                    else:
                        ele = '<a class="showdata1" href="#" topic="{}" title="点击展示数据"><div class="col-md-4"><div class="widget style1 navy-bg"><div class="row"><div class="col-xs-4"><i class="fa fa-gears fa-5x"></i></div><div class="col-xs-8" style="text-align: center"><strong><h2>{}</h2></strong><h1 class="font-bold">{}　{}</h1></div></div></div></div></a>' \
                            .format(object.id, object.devname, data, object.devsym)
                        modelsub_list.append(ele)
                    count = count + 1
                else:
                    if count % 3 == 0:
                        data = "Null"
                        ele = '<a class="showdata1" href="#" topic="{}" title="点击展示数据"><div class="col-md-4"><div class="widget style1 navy-bg"><div class="row"><div class="col-xs-4"><i class="fa fa-gears fa-5x"></i></div><div class="col-xs-8" style="text-align: center"><strong><h2>{}</h2></strong><h1 class="font-bold">{}　{}</h1></div></div></div></div></a>' \
                            .format(object.id, object.devname, data, object.devsym)
                        modelsub_list.append(ele)
                        modelsub_list.append("</div><div class='row'>")
                    else:
                        data = "Null"
                        ele = '<a class="showdata1" href="#" topic="{}" title="点击展示数据"><div class="col-md-4"><div class="widget style1 navy-bg"><div class="row"><div class="col-xs-4"><i class="fa fa-gears fa-5x"></i></div><div class="col-xs-8" style="text-align: center"><strong><h2>{}</h2></strong><h1 class="font-bold">{}　{}</h1></div></div></div></div></a>' \
                            .format(object.id, object.devname, data, object.devsym)
                        modelsub_list.append(ele)
                    count = count + 1
        modelsub_list.append("</div>")

        model_str = mark_safe("".join(modelsub_list))

        return JsonResponse({'status': True, 'data': model_str})
    return JsonResponse({'status': False})


# def videoshow(request):
#     model_video = []
#     objects = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
#         devtype="2").filter(send_flag="1")
#
#     for object in objects:
#         path = object.srcpath
#         if path == None:
#             ele = '<div class="divvideo"><img src="#"}></div>'
#         else:
#             ele = '<div id="{}" class="divvideo"><img src="{}"></div>'.format(object.id , path[1:]+"?"+str(random.random()))
#         model_video.append(ele)
#         model_video = mark_safe("".join(model_video))
#         print(model_video)
#     return JsonResponse({'status': True, 'video': model_video})
# 刷新视频模块展示
def videoshow(request):
    nid = request.GET.get("nid")
    model_video = []
    row_dict = {}
    modelparts = models.ModelPart.objects.filter(ModelID_id=nid)
    weidingyue = './web/static/img/video/weidingyue.jpg'
    if modelparts.exists():
        for modelpart in modelparts:
            object = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
                devtopic=modelpart.reltopic_id).first()
            if object.devtype == '2' and object.send_flag == "1":
                if object.flag == '订阅中':

                    path = object.srcpath
                    if path != None:
                        row_dict[str(object.id)] = path[1:] + "?" + str(random.random())
                        return JsonResponse({'status': True, 'video': row_dict})
                else:
                    row_dict[str(object.id)] = weidingyue[1:] + "?" + str(random.random())
                    return JsonResponse({'status': True, 'video': row_dict})

    return JsonResponse({'status': False})


# help页面
def help(request):
    return render(request, 'help.html')


# 全局可视化页面
def charts(request):
    # timestamp_list = []
    # now = datetime.datetime.now()
    # start = now - datetime.timedelta(hours=3, minutes=0, seconds=0);
    # print(start)
    # a = models.DeviceData.objects.filter(datarecord__gt=start)  # .order_by("-datarecord")
    # timestamp_list = []
    # # i.datarecord.strftime("%Y-%m-%d %H:%M:%S"))
    # for i in a:
    #     w = i.datarecord.strftime("%Y-%m-%d %H:%M:%S")
    #     w = time.strptime(w, '%Y-%m-%d %H:%M:%S')
    #     this_date = time.mktime(w)
    #     timestamp_list.append(this_date * 1000)
    # print(timestamp_list)

    return render(request, 'charts.html')


# 历史数据页面
def datalist(request):
    # 分页通用模板
    page = int(request.GET.get('page', 1))
    page_size = 30
    start = (page - 1) * page_size
    end = page * page_size
    data_dict = {}
    value = request.GET.get('q', '')

    if value:
        if models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
                devtopic__startswith=value).exists():
            id = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
                devtopic__startswith=value).first().id
            data_dict["devtopic_id"] = id
        else:
            return render(request, 'datalist.html', {"value": value})
    page_list = []
    page_count = models.DeviceData.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(**data_dict).count()
    total_count, div = divmod(page_count, page_size)
    if div:
        total_count += 1
    plus = 3
    if total_count <= 2 * plus + 1:
        start_page = 1
        end_page = total_count
    else:
        if page <= plus:
            start_page = 1
            end_page = 2 * plus + 1
        else:
            if (page + plus) > total_count:
                start_page = total_count - 2 * plus
                end_page = total_count
            else:
                start_page = page - plus
                end_page = page + plus
    if page > 1:
        prev = '<li><a href="?page={}&q={}">上一页</a></li>'.format(page - 1, value)
    else:
        prev = '<li><a href="?page={}&q={}">上一页</a></li>'.format(1, value)
    page_list.append(prev)

    for i in range(start_page, end_page + 1):
        if i == page:
            ele = '<li class="active"><a href="?page={}&q={}">{}</a></li>'.format(i, value, i)
        else:
            ele = '<li><a href="?page={}&q={}">{}</a></li>'.format(i, value, i)
        page_list.append(ele)
    if page < total_count:
        next = '<li><a href="?page={}&q={}">下一页</a></li>'.format(page + 1, value)
    else:
        if total_count == 0:
            total_count = 1
        next = '<li><a href="?page={}&q={}">下一页</a></li>'.format(total_count, value)
    page_list.append(next)
    page_str = mark_safe("".join(page_list))
    queryset = models.DeviceData.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(**data_dict).order_by(
        "-datarecord")[start:end]
    datacont = {}
    for querysetm in queryset:

        querysetm.datarecord = querysetm.datarecord.strftime("%Y-%m-%d %H:%M:%S")
        if querysetm.triggerset != None:
            if querysetm.triggerset[0:4] == '触发事件':
                querysetm.devdata = querysetm.devdata + ':' + querysetm.triggerset
                querysetm.datadetail = querysetm.devdata + ':' + querysetm.triggerset
        if len(querysetm.devdata) > 8:
            querysetm.devdata = '{}...'.format(querysetm.devdata[0:8])
        else:
            querysetm.devdata = querysetm.devdata

    request.name = models.UserInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).first().username
    obj = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone)

    return render(request, 'datalist.html',
                  {"queryset": queryset, "value": value, "page_str": page_str, "obj": obj, "datacont": datacont})


@csrf_exempt
def databatchdel(request):
    topic = request.POST.get("topic")
    data = request.POST.get("data")
    try:
        if topic == '未选择':
            return JsonResponse({"status": False})
        deldev = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(devtopic=topic)
        if deldev.exists() and data != None:
            delid = models.DeviceData.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
                devtopic_id=deldev.first().id).order_by('datarecord')
            test = delid[:eval(data)]
            for i in test:
                saveid = i.id

            models.DeviceData.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
                devtopic_id=deldev.first().id).filter(id__lte=saveid).order_by('datarecord').delete()

            return JsonResponse({"status": True})
    except:
        return JsonResponse({"status": False})


# 历史数据删除
def datadel(request):
    nid = request.GET.get('nid')
    try:
        models.DeviceData.objects.filter(id=nid).delete()
        return JsonResponse({"status": True})
    except:
        return JsonResponse({"status": False})


# 管理页面设备删除
def devdel(request):
    nid = request.GET.get('nid')
    print(nid)
    deltopic = models.DevInfo.objects.filter(id=nid).first().devtopic
    srcpath = models.DevInfo.objects.filter(id=nid).first().srcpath
    # 删除时不管是是发布还是订阅都取消订阅一次

    client.unsubscribe(deltopic)
    try:
        if srcpath != None:
            os.remove(srcpath)
    except:
        print("man error remove")
    topic = models.DevInfo.objects.filter(id=nid).first().devtopic
    modelss = models.ModelInfo.objects.filter(mobile_phone=request.tracer.mobile_phone)
    for model in modelss:
        if models.ModelPart.objects.filter(ModelID_id=model.id).filter(reltopic_id=topic).exists():
            models.ModelPart.objects.filter(ModelID_id=model.id).filter(reltopic_id=topic).delete()

    models.DevInfo.objects.filter(id=nid).delete()
    return redirect("/web/device/man/")


# 用户中心页面
def usercenter(request):
    if request.method == 'GET':
        gend_dict = {'男': '男', '女': '女', '未设置': '未设置'}
        userinfo = model_to_dict(models.UserInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).first())
        userinfo.pop("password")
        gend_dict.pop(userinfo['gender'])
        return render(request, 'usercenter.html', {'userinfo': userinfo, 'gend_dict': gend_dict})

    fileobj = request.FILES.get("avatar")
    if fileobj != None:
        img_name = request.tracer.mobile_phone + fileobj.name
        img_name = img_name.split('.')[0]
        img_name = img_name.split(' ')[0]
        img_name = img_name + str(random.randint(1, 1000)) + '.jpg'
        open_str = '/web/static/img/userimg/'
        open_str = open_str + img_name

        imgsrc = models.UserInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).first().imgsrc
        if imgsrc != None:
            print("remove " + imgsrc)
            os.remove("." + imgsrc)
        models.UserInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).update(imgsrc=open_str)
        f = open('.' + open_str, mode='wb')
        for chunk in fileobj.chunks():
            f.write(chunk)
        f.close()

    gend_dict = {'男': '男', '女': '女', '未设置': '未设置'}
    username = request.POST.get("username")
    gender = request.POST.get("gender")
    address = request.POST.get("address")
    detail = request.POST.get("detail")

    models.UserInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).update(username=username)
    models.UserInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).update(gender=gender)
    models.UserInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).update(address=address)
    models.UserInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).update(detail=detail)
    userinfo = model_to_dict(models.UserInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).first())
    userinfo.pop("password")
    gend_dict.pop(userinfo['gender'])
    return render(request, 'usercenter.html', {'userinfo': userinfo, 'gend_dict': gend_dict})


# 用户所有页面
def deviceown(request):
    page = int(request.GET.get('page', 1))
    page_size = 30
    start = (page - 1) * page_size
    end = page * page_size

    data_dict = {}
    value = request.GET.get('q', '')
    if value:
        data_dict["devname"] = value
    page_list = []
    page_count = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(**data_dict).count()
    total_count, div = divmod(page_count, page_size)
    if div:
        total_count += 1
    plus = 5
    if total_count <= 2 * plus + 1:
        start_page = 1
        end_page = total_count
    else:
        if page <= plus:
            start_page = 1
            end_page = 2 * plus + 1
        else:
            if (page + plus) > total_count:
                start_page = total_count - 2 * plus
                end_page = total_count
            else:
                start_page = page - plus
                end_page = page + plus
    if page > 1:
        prev = '<li><a href="?page={}">上一页</a></li>'.format(page - 1)
    else:
        prev = '<li><a href="?page={}">上一页</a></li>'.format(1)
    page_list.append(prev)
    for i in range(start_page, end_page + 1):
        if i == page:
            ele = '<li class="active"><a href="?page={}">{}</a></li>'.format(i, i)
        else:
            ele = '<li><a href="?page={}">{}</a></li>'.format(i, i)
        page_list.append(ele)
    if page < total_count:
        next = '<li><a href="?page={}">下一页</a></li>'.format(page + 1)
    else:
        if total_count == 0:
            total_count = 1
        next = '<li><a href="?page={}">下一页</a></li>'.format(total_count)
    page_list.append(next)
    page_str = mark_safe("".join(page_list))
    queryset = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(**data_dict).order_by(
        "-devrecord")[start:end]
    for querysetm in queryset:
        querysetm.devrecord = querysetm.devrecord.strftime("%Y-%m-%d")
        if len(str(querysetm.detail)) > 6:
            querysetm.detail = '{}...'.format(str(querysetm.detail[0:6]))
        else:
            querysetm.detail = str(querysetm.detail)
        if len(str(querysetm.devname)) > 6:
            querysetm.devname = '{}...'.format(str(querysetm.devname[0:6]))
        else:
            querysetm.devname = str(querysetm.devname)
    request.name = models.UserInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).first().username
    form = DevinfoModelForm(request)
    form1 = DevinfodetailModelForm()
    return render(request, 'deviceown.html',
                  {"queryset": queryset, "value": value, "page_str": page_str, 'form': form, 'form1': form1})


# 设备管理界面
def devman(request):
    page = int(request.GET.get('page', 1))
    page_size = 30
    start = (page - 1) * page_size
    end = page * page_size
    data_dict = {}
    value = request.GET.get('q', '')
    if value:
        data_dict["devname"] = value
    page_list = []
    page_count = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
        **data_dict).count()
    total_count, div = divmod(page_count, page_size)
    if div:
        total_count += 1
    plus = 5
    if total_count <= 2 * plus + 1:
        start_page = 1
        end_page = total_count
    else:
        if page <= plus:
            start_page = 1
            end_page = 2 * plus + 1
        else:
            if (page + plus) > total_count:
                start_page = total_count - 2 * plus
                end_page = total_count
            else:
                start_page = page - plus
                end_page = page + plus
    if page > 1:
        prev = '<li><a href="?page={}">上一页</a></li>'.format(page - 1)
    else:
        prev = '<li><a href="?page={}">上一页</a></li>'.format(1)
    page_list.append(prev)

    for i in range(start_page, end_page + 1):
        if i == page:
            ele = '<li class="active"><a href="?page={}">{}</a></li>'.format(i, i)
        else:
            ele = '<li><a href="?page={}">{}</a></li>'.format(i, i)
        page_list.append(ele)
    if page < total_count:
        next = '<li><a href="?page={}">下一页</a></li>'.format(page + 1)
    else:
        if total_count == 0:
            total_count = 1
        next = '<li><a href="?page={}">下一页</a></li>'.format(total_count)
    page_list.append(next)
    page_str = mark_safe("".join(page_list))

    queryset = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
        **data_dict).order_by(
        "-devrecord")[start:end]
    for querysetm in queryset:
        querysetm.devrecord = querysetm.devrecord.strftime("%Y-%m-%d %H:%M:%S")
        if querysetm.devtype == '1':
            querysetm.devtype = '数据流'
        elif querysetm.devtype == '2':
            querysetm.devtype = '视频流'
        else:
            querysetm.devtype = '未知错误'
    request.name = models.UserInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).first().username
    form = DevinfoModelForm(request)
    return render(request, 'deviceman.html',
                  {"queryset": queryset, "value": value, "page_str": page_str, 'form': form})

# print(request.POST, type(request.POST))
#
# return redirect("/web/device/man/
# 设备添加页面
@csrf_exempt
def devadd(request):
    print(request.POST)
    form = DevinfoModelForm(request, data=request.POST)

    if form.is_valid():
        form.save()
        send_flag = form.cleaned_data['send_flag']
        if send_flag == '2':
            models.DevInfo.objects.filter(send_flag=send_flag).update(flag="待发布")
            print("ok")
        return JsonResponse({'status': True, 'data': '/web/device/man/'})
    print("no")
    return JsonResponse({'status': False, 'error': form.errors})

# 设备修改详情ajax
@csrf_exempt
def devdetail(request):
    if request.method == 'GET':
        uid = request.GET.get("uid")
        obj = models.DevInfo.objects.filter(id=uid).values("mobile_phone", "devname", "send_flag", "devtopic", "devsym",
                                                           "devtype", "detail", "devrecord").first()
        if not obj:
            return JsonResponse({"status": False, 'error': "不存在信息"})
        obj["devrecord"] = obj["devrecord"].strftime("%Y-%m-%d %H:%M:%S")
        print(obj["devrecord"])
        return JsonResponse({"status": True, "data": obj})

    devtopic = request.POST.get('devtopic1')
    devname = request.POST.get('devname1')
    sendflag = request.POST.get('send_flag1')
    devsym = request.POST.get('devsym1')
    devtype = request.POST.get('devtype1')
    detail = request.POST.get('detail1')

    models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(devtopic=devtopic).update(
        devname=devname)
    models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(devtopic=devtopic).update(
        send_flag=sendflag)
    models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(devtopic=devtopic).update(
        devsym=devsym)
    models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(devtopic=devtopic).update(
        devtype=devtype)
    models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(devtopic=devtopic).update(
        detail=detail)
    return JsonResponse({"status": True})


# 设备管理页面订阅与发布
def devsub(request):
    subid = request.GET.get("subid")
    print(subid)
    obj = models.DevInfo.objects.filter(id=subid).first()
    print(obj.flag)
    if obj.flag == "未订阅":
        client.subscribe(obj.devtopic)
        client.loop_start()
        print("subsrcibe", obj.devtopic)
        models.DevInfo.objects.filter(id=subid).update(flag="订阅中")
        return JsonResponse({"status": True})
    elif obj.flag == "订阅中":
        client.unsubscribe(obj.devtopic)
        print("unsubsrcibe", obj.devtopic)
        models.DevInfo.objects.filter(id=subid).update(flag="未订阅")
        return JsonResponse({"status": False})

global end_time


def oneline(request):
    global end_time
    topic_id = request.GET.get('topic_id')
    count = request.GET.get('count')
    obj = models.DevInfo.objects.filter(id=topic_id).first()
    legend = []
    legend.append(obj.devname)
    datalist = []
    x = []
    datas = models.DeviceData.objects.filter(devtopic=topic_id).order_by("-datarecord")[0:eval(count):-1]
    for data in datas:
        datalist.append(data.devdata)

        end_time = data.datarecord
        x.append(str(data.datarecord.strftime("%Y-%m-%d %H:%M:%S")))

    result = {
        "status": True,
        "data": {
            'legend': legend,
            'name': obj.devname,
            'y': datalist,
            'x': x,
        }
    }
    return JsonResponse(result)


def flushdata(request):
    global end_time
    topic_id = request.GET.get('topic_id')
    datas = models.DeviceData.objects.filter(devtopic=topic_id).filter(datarecord__gt=end_time).order_by(
        "datarecord")
    if datas.exists():
        data = datas.first()
        end_time = data.datarecord
        x = str(data.datarecord.strftime("%Y-%m-%d %H:%M:%S"))
        y = data.devdata
        result = {
            "status": True,
            "data": {
                'x': x,
                'y': y,
            }
        }
        return JsonResponse(result)
    return JsonResponse({"status": False})


def scheduleshow(request):
    perhour = []
    perminute = []
    for i in range(0, 24):
        if i < 10:
            perhour.append('0' + str(i))
        else:
            perhour.append(str(i))
    for i in range(0, 60):
        if i < 10:
            perminute.append('0' + str(i))
        else:
            perminute.append(str(i))

    pubobj = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(send_flag='2')
    list = models.Scheduletask.objects.filter(mobile_phone=request.tracer.mobile_phone).order_by('-tasksavetime')
    for i in list:
        i.tasksavetime = i.tasksavetime.strftime("%Y-%m-%d %H:%M:%S")
    return render(request, 'schedule.html',
                  {"perhour": perhour, "perminute": perminute, "pubobj": pubobj, "list": list})


def tasksub(name):
    task_topic = name.get('task_topic')
    task_cont = name.get('task_cont')
    phone = name.get('phone')
    pub_str = '{"data":"%s","type":"web"}' % (task_cont)
    print("pub", pub_str)
    buffer = json.dumps(eval(pub_str))
    client.publish(task_topic, buffer, qos=0)
    devtopicpk = models.DevInfo.objects.get(devtopic=task_topic)
    pubsav = models.DeviceData(mobile_phone=phone, devdata=str(task_cont), datadetail=str(task_cont), send_flag='发布',
                               devtopic_id=devtopicpk.id)
    pubsav.save()


def scheduledel(request):
    nid = request.GET.get('nid')
    try:
        obj = models.Scheduletask.objects.filter(id=nid)
        schedule.clear(obj.first().taskname)
        obj.delete()
        return JsonResponse({"status": True})
    except:
        return JsonResponse({"status": False})


def scheduledetail(request):
    nid = request.GET.get('nid')
    objs = models.Scheduletask.objects.filter(id=nid)
    if objs.exists():
        obj = objs.first()
        if obj.tasktype == '周期不截止-固定时分':
            str1 = '识别为天计划，预计在每天的{}时{}分'.format(obj.taskhour, obj.taskminute)
            str2 = '发布数据为<{}>'.format(obj.taskcont)
            str3 = ''
            str4 = '向主题 <{}>'.format(obj.tasktopic)
        if obj.tasktype == '周期不截止-每时每分':
            str1 = '识别为天计划，预计在每天基于产生事件的每时每分'
            str2 = '发布数据为<{}>'.format(obj.taskcont)
            str3 = ''
            str4 = '向主题 <{}>'.format(obj.tasktopic)
        if obj.tasktype == '周期不截止-每时固定分':
            str1 = '识别为周计划，预计在{}的{}分'.format(obj.taskhour, obj.taskminute)
            str2 = '发布数据为<{}>'.format(obj.taskcont)
            str3 = ''
            str4 = '向主题 <{}>'.format(obj.tasktopic)
        if obj.tasktype == '周期不截止-固定周时分':
            str1 = '识别为周计划，预计在{}的{}时{}分'.format(obj.taskweek, obj.taskhour, obj.taskminute)
            str2 = '发布数据为<{}>'.format(obj.taskcont)
            str3 = ''
            str4 = '向主题 <{}>'.format(obj.tasktopic)
        if obj.tasktype == '周期截止-每时每分':
            str1 = '识别为天计划，预计在每天基于产生事件的每时每分'
            str2 = '发布数据为<{}>'.format(obj.taskcont)
            str3 = '并将于{}截止'.format(obj.taskuptodate)
            str4 = '向主题 <{}>'.format(obj.tasktopic)
        if obj.tasktype == '周期截止-每时固定分':
            str1 = '识别为天计划，预计在每天的{}时{}分'.format(obj.taskhour, obj.taskminute)
            str2 = '发布数据为<{}>'.format(obj.taskcont)
            str3 = '并将于{}截止'.format(obj.taskuptodate)
            str4 = '向主题 <{}>'.format(obj.tasktopic)
        if obj.tasktype == '周期截止-固定周时分':
            str1 = '识别为周计划，预计在{}的{}时{}分'.format(obj.taskweek, obj.taskhour, obj.taskminute)
            str2 = '发布数据为<{}>'.format(obj.taskcont)
            str3 = '并将于{}截止'.format(obj.taskuptodate)
            str4 = '向主题 <{}>'.format(obj.tasktopic)
        if obj.tasktype == '周期截止-单次发布':
            str1 = '识别为单次发送，预计在{}天后的{}时{}分'.format(obj.taskweek, obj.taskhour, obj.taskminute)
            str2 = '发布数据为<{}>'.format(obj.taskcont)
            str3 = ''
            str4 = '向主题 <{}>'.format(obj.tasktopic)
    return JsonResponse({"status": True, 'str1': str1, 'str2': str4, 'str3': str2, 'str4': str3, 'flag': obj.flag})


@csrf_exempt
def pubplan1(request):
    task_name = request.POST.get("taskname1")
    task_topic = request.POST.get("tasktopic1")
    task_cont = request.POST.get("taskcont1")
    task_hour = request.POST.get("taskhour1")
    task_minute = request.POST.get("taskminute1")
    if task_name == '' or task_cont == '' or task_hour == '未选择' or task_minute == '未选择' or task_topic == '未选择':
        return JsonResponse({'status': False})

    if models.Scheduletask.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(taskname=task_name).exists():
        return JsonResponse({'status': False, 'error': "存在任务名"})

    sub_para = {"task_topic": task_topic, "task_cont": task_cont, "phone": request.tracer.mobile_phone}
    try:
        if task_hour == '每小时':
            if task_minute == '每分钟':
                schedule.every().minutes.do(tasksub, sub_para).tag(task_name)
                id = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
                    devtopic=task_topic).first().id
                obj = models.Scheduletask(taskname=task_name, taskcont=task_cont, tasktopic_id=id, taskhour=task_hour,
                                          taskminute=task_minute, flag='有效', tasktype='周期不截止-每时每分',
                                          mobile_phone=request.tracer.mobile_phone)
                obj.save();
            # 每周每小时的固定分
            else:
                time_str = ':' + task_minute
                schedule.every().hour.at(time_str).do(tasksub, sub_para).tag(task_name)
                id = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
                    devtopic=task_topic).first().id
                obj = models.Scheduletask(taskname=task_name, taskcont=task_cont, tasktopic_id=id, taskhour=task_hour,
                                          taskminute=task_minute, flag='有效', tasktype='周期不截止-每时固定分',
                                          mobile_phone=request.tracer.mobile_phone)
                obj.save();
        # 每天固定时分
        else:
            if task_minute == '每分钟':
                return JsonResponse({'status': False, 'error': '暂不支持该用法'})
            time_str = task_hour + ':' + task_minute
            schedule.every().day.at(time_str).do(tasksub, sub_para).tag(task_name)
            id = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
                devtopic=task_topic).first().id
            obj = models.Scheduletask(taskname=task_name, taskcont=task_cont, tasktopic_id=id, taskhour=task_hour,
                                      taskminute=task_minute, flag='有效', tasktype='周期不截止-固定时分',
                                      mobile_phone=request.tracer.mobile_phone)
            obj.save();
        return JsonResponse({'status': True})
    except:
        return JsonResponse({'status': False})


@csrf_exempt
def pubplan2(request):
    task_name = request.POST.get("taskname2")
    task_topic = request.POST.get("tasktopic2")
    task_cont = request.POST.get("taskcont2")
    task_week = request.POST.get("taskweek2")
    task_hour = request.POST.get("taskhour2")
    task_minute = request.POST.get("taskminute2")

    if task_name == '' or task_cont == '' or task_week == '未选择' or task_hour == '未选择' or task_minute == '未选择' or task_topic == '未选择':
        return JsonResponse({'status': False})
    if models.Scheduletask.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(taskname=task_name).exists():
        return JsonResponse({'status': False, 'error': "存在任务名"})

    sub_para = {"task_topic": task_topic, "task_cont": task_cont, "phone": request.tracer.mobile_phone}
    try:
        if task_week == '每天':
            time_str = task_hour + ':' + task_minute
            schedule.every().day.at(time_str).do(tasksub, sub_para).tag(task_name)
        elif task_week == '每周一':
            time_str = task_hour + ':' + task_minute
            schedule.every().monday.at(time_str).do(tasksub, sub_para).tag(task_name)
        elif task_week == '每周二':
            time_str = task_hour + ':' + task_minute
            schedule.every().tuesday.at(time_str).do(tasksub, sub_para).tag(task_name)
        elif task_week == '每周三':
            time_str = task_hour + ':' + task_minute
            schedule.every().wednesday.at(time_str).do(tasksub, sub_para).tag(task_name)
        elif task_week == '每周四':
            time_str = task_hour + ':' + task_minute
            schedule.every().thursday.at(time_str).do(tasksub, sub_para).tag(task_name)
        elif task_week == '每周五':
            time_str = task_hour + ':' + task_minute
            schedule.every().friday.at(time_str).do(tasksub, sub_para).tag(task_name)
        elif task_week == '每周六':
            time_str = task_hour + ':' + task_minute
            schedule.every().saturday.at(time_str).do(tasksub, sub_para).tag(task_name)
        elif task_week == '每周天':
            time_str = task_hour + ':' + task_minute
            schedule.every().sunday.at(time_str).do(tasksub, sub_para).tag(task_name)
        id = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
            devtopic=task_topic).first().id
        obj = models.Scheduletask(taskname=task_name, taskcont=task_cont, tasktopic_id=id, taskweek=task_week,
                                  taskhour=task_hour,
                                  taskminute=task_minute, flag='有效', tasktype='周期不截止-固定周时分',
                                  mobile_phone=request.tracer.mobile_phone)
        obj.save();
        return JsonResponse({'status': True})
    except:
        return JsonResponse({'status': False})


@csrf_exempt
def pubplan3(request):
    task_name = request.POST.get("taskname")
    task_topic = request.POST.get("tasktopic")
    task_cont = request.POST.get("taskcont")
    task_hour = request.POST.get("taskhour")
    task_minute = request.POST.get("taskminute")
    task_uptodate = request.POST.get("taskuptodate")
    if task_name == '' or task_cont == '' or task_hour == '未选择' or task_minute == '未选择' or task_topic == '未选择' or task_uptodate == '':
        return JsonResponse({'status': False})

    if models.Scheduletask.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(taskname=task_name).exists():
        return JsonResponse({'status': False, 'error': "存在任务名"})

    sub_para = {"task_topic": task_topic, "task_cont": task_cont, "phone": request.tracer.mobile_phone}
    try:
        if task_hour == '每小时':
            if task_minute == '每分钟':
                schedule.every().minutes.until(task_uptodate).do(tasksub, sub_para).tag(task_name)
                id = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
                    devtopic=task_topic).first().id
                obj = models.Scheduletask(taskname=task_name, taskcont=task_cont, tasktopic_id=id, taskhour=task_hour,
                                          taskminute=task_minute, taskuptodate=task_uptodate, flag='有效',
                                          tasktype='周期截止-每时每分',
                                          mobile_phone=request.tracer.mobile_phone)
                obj.save();
            # 每周每小时的固定分
            else:
                time_str = ':' + task_minute
                schedule.every().hour.at(time_str).until(task_uptodate).do(tasksub, sub_para).tag(task_name)
                id = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
                    devtopic=task_topic).first().id
                obj = models.Scheduletask(taskname=task_name, taskcont=task_cont, tasktopic_id=id, taskhour=task_hour,
                                          taskminute=task_minute, taskuptodate=task_uptodate, flag='有效',
                                          tasktype='周期截止-每时固定分',
                                          mobile_phone=request.tracer.mobile_phone)
                obj.save();
        # 每天固定时分
        else:
            if task_minute == '每分钟':
                return JsonResponse({'status': False, 'error': '暂不支持该用法'})
            time_str = task_hour + ':' + task_minute
            schedule.every().day.at(time_str).until(task_uptodate).do(tasksub, sub_para).tag(task_name)
            id = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
                devtopic=task_topic).first().id
            obj = models.Scheduletask(taskname=task_name, taskcont=task_cont, tasktopic_id=id, taskhour=task_hour,
                                      taskminute=task_minute, flag='有效', taskuptodate=task_uptodate,
                                      tasktype='周期截止-固定时分',
                                      mobile_phone=request.tracer.mobile_phone)
            obj.save();
        return JsonResponse({'status': True})
    except:
        return JsonResponse({'status': False})


@csrf_exempt
def pubplan4(request):
    task_name = request.POST.get("taskname")
    task_topic = request.POST.get("tasktopic")
    task_cont = request.POST.get("taskcont")
    task_week = request.POST.get("taskweek")
    task_hour = request.POST.get("taskhour")
    task_minute = request.POST.get("taskminute")
    task_uptodate = request.POST.get("taskuptodate")

    if task_name == '' or task_cont == '' or task_week == '未选择' or task_hour == '未选择' or task_minute == '未选择' or task_topic == '未选择':
        return JsonResponse({'status': False})
    if models.Scheduletask.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(taskname=task_name).exists():
        return JsonResponse({'status': False, 'error': "存在任务名"})

    sub_para = {"task_topic": task_topic, "task_cont": task_cont, "phone": request.tracer.mobile_phone}
    try:
        if task_week == '每天':
            time_str = task_hour + ':' + task_minute
            schedule.every().day.at(time_str).until(task_uptodate).do(tasksub, sub_para).tag(task_name)
        elif task_week == '每周一':
            time_str = task_hour + ':' + task_minute
            schedule.every().monday.at(time_str).until(task_uptodate).do(tasksub, sub_para).tag(task_name)
        elif task_week == '每周二':
            time_str = task_hour + ':' + task_minute
            schedule.every().tuesday.at(time_str).until(task_uptodate).do(tasksub, sub_para).tag(task_name)
        elif task_week == '每周三':
            time_str = task_hour + ':' + task_minute
            schedule.every().wednesday.at(time_str).until(task_uptodate).do(tasksub, sub_para).tag(task_name)
        elif task_week == '每周四':
            time_str = task_hour + ':' + task_minute
            schedule.every().thursday.at(time_str).until(task_uptodate).do(tasksub, sub_para).tag(task_name)
        elif task_week == '每周五':
            time_str = task_hour + ':' + task_minute
            schedule.every().friday.at(time_str).until(task_uptodate).do(tasksub, sub_para).tag(task_name)
        elif task_week == '每周六':
            time_str = task_hour + ':' + task_minute
            schedule.every().saturday.at(time_str).until(task_uptodate).do(tasksub, sub_para).tag(task_name)
        elif task_week == '每周天':
            time_str = task_hour + ':' + task_minute
            schedule.every().sunday.at(time_str).until(task_uptodate).do(tasksub, sub_para).tag(task_name)
        id = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
            devtopic=task_topic).first().id
        obj = models.Scheduletask(taskname=task_name, taskcont=task_cont, tasktopic_id=id, taskweek=task_week,
                                  taskhour=task_hour,
                                  taskminute=task_minute, flag='有效', taskuptodate=task_uptodate,
                                  tasktype='周期截止-固定周时分',
                                  mobile_phone=request.tracer.mobile_phone)
        obj.save();
        return JsonResponse({'status': True})
    except:
        return JsonResponse({'status': False})


def job_that_executes_once(name):
    task_topic = name.get('task_topic')
    task_cont = name.get('task_cont')
    phone = name.get('phone')
    pub_str = '{"data":"%s","type":"web"}' % (task_cont)
    buffer = json.dumps(eval(pub_str))
    client.publish(task_topic, buffer, qos=0)
    devtopicpk = models.DevInfo.objects.get(devtopic=task_topic)
    pubsav = models.DeviceData(mobile_phone=phone, devdata=str(task_cont), datadetail=str(task_cont), send_flag='发布',
                               devtopic_id=devtopicpk.devtopic)
    pubsav.save()
    return schedule.CancelJob


@csrf_exempt
def pubplan5(request):
    task_name = request.POST.get("taskname")
    task_topic = request.POST.get("tasktopic")
    task_cont = request.POST.get("taskcont")
    task_week = request.POST.get("taskweek")
    task_hour = request.POST.get("taskhour")
    task_minute = request.POST.get("taskminute")
    if task_name == '' or task_cont == '' or task_week == '' or task_hour == '未选择' or task_minute == '未选择' or task_topic == '未选择':
        return JsonResponse({'status': False})
    if models.Scheduletask.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(taskname=task_name).exists():
        return JsonResponse({'status': False, 'error': "存在任务名"})

    time_str = task_hour + ':' + task_minute
    sub_para = {"task_topic": task_topic, "task_cont": task_cont, 'phone': request.tracer.mobile_phone}

    schedule.every(eval(task_week)).days.at(time_str).do(job_that_executes_once, sub_para).tag(task_name)
    id = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
        devtopic=task_topic).first().id
    obj = models.Scheduletask(taskname=task_name, taskcont=task_cont, tasktopic_id=id, taskweek=task_week,
                              taskhour=task_hour,
                              taskminute=task_minute, flag='有效',
                              tasktype='周期截止-单次发布',
                              mobile_phone=request.tracer.mobile_phone)
    obj.save()
    schedule.clear(task_name)
    return JsonResponse({'status': True})


def triggershow(request):
    subobjs = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(send_flag='1');
    pubobjs = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(send_flag='2');
    showobjs = models.Trigger.objects.filter(mobile_phone=request.tracer.mobile_phone);

    return render(request, "trigger.html", {'triggercalling': subobjs, 'triggercalled': pubobjs, 'showobjs': showobjs})


@csrf_exempt
def triggersave(request):
    triggername = request.POST.get("triggername")
    triggercalling = request.POST.get("triggercalling")
    triggerdata = request.POST.get("triggerdata")
    triggercalled = request.POST.get("triggercalled")
    pubdata = request.POST.get("pubdata")
    savetime = '未触发'
    if triggername == '' or triggercalling == '未选择' or triggercalled == '未选择' or triggerdata == '' or pubdata == '':
        return JsonResponse({"status": False})
    if models.Trigger.objects.filter(triggername=triggername).exists():
        return JsonResponse({"status": False, "error": "任务名重复"})
    obj = models.Trigger(triggername=triggername, triggercalling=triggercalling, triggercalled=triggercalled,
                         triggerdata=triggerdata, pubdata=pubdata, triggersavetime=savetime,
                         mobile_phone=request.tracer.mobile_phone)
    obj.save()
    return JsonResponse({"status": True})


def triggerdel(request):
    nid = request.GET.get('nid')
    try:
        obj = models.Trigger.objects.filter(id=nid)
        obj.delete()
        return JsonResponse({"status": True})
    except:
        return JsonResponse({"status": False})


def triggercheck(request):
    nid = request.GET.get('nid')
    list = []
    listact = []
    count = 0
    try:
        obj = models.Trigger.objects.filter(id=nid).first()
        id = models.DevInfo.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(
            devtopic=obj.triggercalling).first().id
        data = models.DeviceData.objects.filter(mobile_phone=request.tracer.mobile_phone).filter(devtopic_id=id)
        if data.exists():
            for i in data:
                if i.triggerset[0:4] == "触发事件" and i.triggerset[4:] == obj.triggername:
                    time = i.datarecord.strftime("%Y-%m-%d %H:%M:%S")
                    ele = "<div style='height: 40px'>{}</div>".format(time)
                    list.append(ele)

                    ele = "<div style='height: 40px'><a id='{}' class='btn btn-primary btndell'>确认并删除</a></div>".format(
                        i.id)
                    listact.append(ele)
                    count += 1
            if count != 0:
                liststr = mark_safe("".join(list))
                listactstr = mark_safe("".join(listact))
                return JsonResponse({"status": True, "list": liststr, "listact": listactstr})
            else:
                ele = "<div style='height: 40px'>{}</div>".format('Null')
                list.append(ele)
                liststr = mark_safe("".join(list))
                return JsonResponse({"status": True, "list": liststr, "listact": ' '})
        else:
            ele = "<div style='height: 40px'>{}</div>".format('Null')
            list.append(ele)
            liststr = mark_safe("".join(list))
            return JsonResponse({"status": True, "list": liststr, "listact": ' '})
    except:
        return JsonResponse({"status": False})


def triggercheckdel(request):
    id = request.GET.get('id')
    try:
        models.DeviceData.objects.filter(id=id).delete()
        return JsonResponse({"status": True})
    except:
        return JsonResponse({"status": False})
